package com.wcity.manage.web.community;

import com.wcity.manage.common.bean.RetBean;
import com.wcity.manage.common.context.Constants;
import com.wcity.manage.common.context.SessionKey;
import com.wcity.manage.common.enums.Code;
import com.wcity.manage.common.exception.CustomException;
import com.wcity.manage.common.utils.DwzUtil;
import com.wcity.manage.common.utils.JSONUtil;
import com.wcity.manage.common.utils.RespUtil;
import com.wcity.manage.common.utils.request.RequestUtil;
import com.wcity.manage.common.vo.community.permit.ConsultationVo;
import com.wcity.manage.dao.dal.model.PageModel;
import com.wcity.manage.dao.model.Block;
import com.wcity.manage.dao.model.Register;
import com.wcity.manage.dao.model.User;
import com.wcity.manage.dao.model.community.permit.Consultation;
import com.wcity.manage.dao.model.community.remark.CommunityRemark;
import com.wcity.manage.service.BlockService;
import com.wcity.manage.service.RegisterService;
import com.wcity.manage.service.community.consultation.ConsultationService;
import com.wcity.manage.service.community.remark.CommunityRemarkService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 社区咨询服务
 * Created by hgg on 2016/12/19.
 */
@Controller
public class ConsultationAct {

    private final static Logger log = LoggerFactory.getLogger( ConsultationAct.class );

    @Autowired
    private ConsultationService consultationService;

    @Autowired
    private CommunityRemarkService communityRemarkService;

    @Autowired
    private BlockService blockService;
    @Autowired
    private RegisterService registerService;

    /**
     * 社区咨询服务列表
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/community_consultation_list")
    public String consultationList( HttpServletRequest request, PageModel model,HttpServletResponse response ) {

        try {

            //【1】封装参数/参数校验
            Map<String, Object> requestMap = RequestUtil.getGetData( request );

            //【2】获取当前用户信息
            User user = (User)request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if( user == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【3】查询数据
            requestMap.put( "start", ( model.getPageNum() - 1) * model.getNumPerPage() );
            requestMap.put( "end", model.getNumPerPage() );
            requestMap.put( "communityUserId", user.getId() );
            List<ConsultationVo> consultationVos = consultationService.consultationPageList( requestMap );

            //【4】查询总数量
            Integer totalConsultation = consultationService.totalConsultation( requestMap );
            model.setTotal( totalConsultation );

            request.setAttribute( "consultations", consultationVos );
            request.setAttribute( "pageModel", model );
            request.setAttribute( "blockId", requestMap.get( "blockId" ) );
            request.setAttribute( "status", requestMap.get( "status" ) == null ? -1 : requestMap.get( "status" ) );

            //【5】查询用户管理的小区列表
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put( "userId",user.getId() );
            List<Block> blocks = blockService.getAdminHaveBlockList( queryMap );
            request.setAttribute( "blocks",blocks );
        } catch ( Exception e ) {
            log.error( "查询社区咨询服务列表异常:" + e.getMessage() );
        }
        return "community/consultation/list";
    }

    /**
     * 执行删除社区咨询服务
     *
     * @param request
     */
    @RequestMapping(value = "delete_community_consultation")
    @ResponseBody
    public void deleteConsultation( HttpServletRequest request, HttpServletResponse response ) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "删除成功";
        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if (requestMap.get("id") == null) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "请选择一条记录", "", "", "", ""));
                return;
            }

            //【2】执行删除
            Integer deleteNum = consultationService.deleteConsultation( requestMap );
            if ( deleteNum == 0 ) {
                code = Constants.STATUS_ERROR_DWZ;
                message = "删除失败";
            }
        } catch ( Exception e ) {
            log.error( "删除社区咨询服务异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "删除失败";
        }
        RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(code, message, "", "", "", ""));
    }

    /**
     * 跳转到社区咨询服务详情页面
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "to_detail_community_consultation")
    public String consultationDetail( HttpServletRequest request, HttpServletResponse response ) {

        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if ( requestMap.get("id") == null ) {
                return null;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if ( user == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【3】查询社区咨询服务数据
            requestMap.put("communityUserId", user.getId());
            ConsultationVo consultationVo = consultationService.consultationDetail( requestMap );
            request.setAttribute( "consultation", consultationVo );
            if (consultationVo == null) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "数据不存在", "", "", "", ""));
                return null;
            }

            //【4】查询相关备注信息
            requestMap.clear();
            requestMap.put( "referId",consultationVo.getId() );
            requestMap.put( "remarkType","consultation" );
            List<CommunityRemark> remarks = communityRemarkService.remarkList( requestMap );
            request.setAttribute( "remarks",remarks );

        } catch ( Exception e ) {
            log.error( "查询社区咨询服务失败: " + e.getMessage() );
            RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "查询失败", "", "", "", ""));
        }

        return "community/consultation/detail";
    }

    /**
     * 跳转到回复社区咨询服务页面
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "to_reply_community_consultation")
    public String consultationReply( HttpServletRequest request, HttpServletResponse response ) {

        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if ( requestMap.get("id") == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "参数错误", "", "community_consultation_list", "", "" ) );
                return null;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if ( user == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "community_consultation_list", "", "" ) );
                return null;
            }

            //【3】查看社区咨询服务状态
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put( "communityUserId",user.getId() );
            queryMap.put( "id",requestMap.get("id") );
            ConsultationVo consultationVo = consultationService.consultationDetail( queryMap );
            if( consultationVo == null || consultationVo.getStatus() == 1 ){
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "您已经回复过了", "", "community_consultation_list", "", ""));
                return null;
            }

            request.setAttribute( "askIngContent",consultationVo.getAskIngContent() );
            request.setAttribute( "consultationId",requestMap.get("id") );
        } catch ( Exception e ) {
            RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "查询失败", "", "", "", ""));
        }

        return "community/consultation/reply";
    }

    /**
     * 跳转到添加备注页面
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "to_add_remark_community_consultation")
        public String consultationAddRemark( HttpServletRequest request, HttpServletResponse response ) {

        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if ( requestMap.get("id") == null ) {
                return null;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if ( user == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            request.setAttribute( "consultationId",requestMap.get("id") );
        } catch ( Exception e ) {
            RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "查询失败", "", "", "", ""));
        }

        return "community/consultation/add-remark";
    }

    /**
     * 保存回复社区咨询服务
     *
     * @param consultation
     * @param response
     */
    @RequestMapping(value = "save_edit_community_consultation")
    @ResponseBody
    public void updateConsultation( Consultation consultation, HttpServletResponse response, HttpServletRequest request ) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "回复成功";

        try {

            //【1】校验参数
            if ( StringUtils.isBlank( consultation.getReplyContent() ) || consultation.getId() == 0 || consultation.getId() == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "参数错误", "", "", "", ""));
                return;
            }

            //【2】获取用户
            User user = (User) request.getSession().getAttribute(SessionKey.SESSION_USER_INFO);
            if (user == null) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", ""));
                return;
            }

            //【3】查看社区咨询服务状态
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put( "communityUserId",user.getId() );
            queryMap.put( "id",consultation.getId() );
            ConsultationVo consultationVo = consultationService.consultationDetail( queryMap );
            if( consultationVo == null || consultationVo.getStatus() == 2 ){
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "您已经回复过了", "", "", "", ""));
                return;
            }

            //【3】执行更新社区咨询服务
            consultation.setUserId( consultationVo.getUserId() );
            consultation.setStatus( 1 );
            consultation.setReplyTime( new Date() );
            Integer updateNum = consultationService.saveUpdateConsultation( consultation );
            if ( updateNum == 0 ) {
                throw new RuntimeException( "更新社区咨询服务失败" );
            }

        } catch ( Exception e ) {
            log.error( "更新社区咨询服务异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "回复失败";
        }
        RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(code, message, "community_consultation_list", "", "closeCurrent", ""));
    }

    /**
     * 执行保存备注
     * @return
     */
    @RequestMapping(value = "save_add_remark_community_consultation")
    public void saveAddRemark( HttpServletRequest request,HttpServletResponse response,CommunityRemark communityRemark ){

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "添加成功";
        try {

            //【1】校验参数
            if ( StringUtils.isBlank( communityRemark.getRemark() ) ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "参数错误", "", "", "", ""));
                return;
            }

            //【2】获取用户
            User user = (User) request.getSession().getAttribute(SessionKey.SESSION_USER_INFO);
            if (user == null) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", ""));
                return;
            }
            //【3】执行保存备注
            communityRemark.setRemarkType( "consultation" );
            Integer saveNum = communityRemarkService.saveAddRemark( communityRemark );
            if( saveNum == 0 ){
                code = Constants.STATUS_ERROR_DWZ;
                message = "添加失败";
            }
        }catch ( Exception e ){
            log.error( "添加社区咨询服务备注失败:" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "添加失败";
        }
        RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(code, message, "community_consultation_list", "", "closeCurrent", ""));
    }

    /****************************************H5端请求处理*********************************************/
    /**
     * 新增社区咨询服务(H5)
     *
     * @param consultation
     * @param response
     */
    @RequestMapping(value = "v1/save_add_community_consultation_h5")
    @ResponseBody
    public RetBean addConsultation( Consultation consultation, HttpServletResponse response, HttpServletRequest request ) {

        //【1】校验参数
        String registerId = request.getParameter( "registerId" );
        if( StringUtils.isBlank( registerId ) || StringUtils.isBlank( consultation.getAskIngContent() ) ){
            throw new CustomException( Constants.PARAMETER_ERROR, Code.ERROR );
        }

        //【2】获取当前用户信息
        Map<String,Object> userMap = (Map<String,Object>)registerService.registerInfo( registerId );
        if( userMap == null || userMap.get( "blockId" ) == null ){
            throw new CustomException( "用户信息不存在", Code.ERROR );
        }

        //【3】执行保存社区咨询服务
        consultation.setUserId( Integer.parseInt( registerId ) );
        consultation.setBlockId( (Integer) userMap.get( "blockId" ) );
        consultation.setStatus( 0 );
        Integer num = 0;
        try {
            num = consultationService.saveAddConsultation( consultation );
        }catch ( Exception e ){
            log.error( "保存失败:" + e.getMessage() );
        }
        if( num == 0 ){
            return new RetBean( Code.ERROR, "保存失败" );
        }else {
            return new RetBean( Code.SUCCESS, "保存成功" );
        }
    }

    /**
     * 社区咨询服务列表
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "v1/community_consultation_list_user")
    @ResponseBody
    public Object myConsultationList( HttpServletRequest request, PageModel model,HttpServletResponse response ) {

        try {

            //【1】校验参数
            String registerId = request.getParameter( "registerId" );
            if( StringUtils.isBlank( registerId ) ){
                throw new CustomException( Constants.PARAMETER_ERROR, Code.ERROR );
            }

            //【2】获取当前用户信息
            Map<String,Object> userMap = (Map<String,Object>)registerService.registerInfo( registerId );
            if( userMap == null || userMap.get( "blockId" ) == null ){
                throw new CustomException( "用户信息不存在", Code.ERROR );
            }

            //【3】封装参数/参数校验
            Map<String, Object> requestMap = new HashedMap();

            //【4】查询数据
            requestMap.put( "start", ( model.getPageNum() - 1) * model.getNumPerPage() );
            requestMap.put( "end", model.getNumPerPage() );
            requestMap.put( "blockId",userMap.get( "blockId" ) );
            List<ConsultationVo> consultationVos = consultationService.consultationPageList( requestMap );

            //【5】查询总数量
            Integer totalConsultation = consultationService.totalConsultation( requestMap );
            model.setTotal( totalConsultation );
            Map<String,Object> map = JSONUtil.getSuccessJson();
            map.put( "consultations", consultationVos );
            map.put( "pageModel", model );
            return map;
        } catch ( Exception e ) {
            log.error( "查询社区咨询服务列表异常:" + e.getMessage() );
            return null;
        }
    }

    /**
     * 跳转到社区咨询服务详情页面
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "v1/detail_community_consultation_h5")
    @ResponseBody
    public Object myConsultationDetail( HttpServletRequest request, HttpServletResponse response ) {

        try {

            //【1】校验参数
            String registerId = request.getParameter( "registerId" );
            String id = request.getParameter( "id" );
            if( StringUtils.isBlank( registerId ) || StringUtils.isBlank( id ) ){
                throw new CustomException( Constants.PARAMETER_ERROR, Code.ERROR );
            }

            //【2】获取当前用户信息
            Map<String,Object> userMap = (Map<String,Object>)registerService.registerInfo( registerId );
            if( userMap == null || userMap.get( "blockId" ) == null ){
                throw new CustomException( "用户信息不存在", Code.ERROR );
            }

            //【3】查询社区咨询服务数据
            Map<String, Object> requestMap = new HashedMap();
            requestMap.put( "blockId", userMap.get( "blockId" ) );
            requestMap.put( "id", Integer.parseInt( id ) );
            ConsultationVo consultationVo = consultationService.consultationDetail( requestMap );
            request.setAttribute( "consultation", consultationVo );
            if (consultationVo == null) {
                return null;
            }

            Map<String,Object> map = JSONUtil.getSuccessJson();
            map.put( "data", consultationVo );
            return map;
        } catch ( Exception e ) {
            log.error( "查询社区咨询服务失败: " + e.getMessage() );
            return null;
        }
    }


}
